﻿Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Xml

Public Class clsEventSales

    Dim sDocEntry As String = String.Empty
    Dim oDTDistinctHeader As DataTable = Nothing
    Dim oDTDistinctLine As DataTable = Nothing

    Dim oDataViewHeader As DataView = Nothing
    Dim oDataViewLine As DataView = Nothing
    Dim oDataViewPayment As DataView = Nothing
    Dim lRetCode As Long
    Dim oUpdateSataus As clsARInvoice = New clsARInvoice

    Public Function UpdateEvent(ByVal oDataset As DataSet, ByVal oDICompany As SAPbobsCOM.Company, ByRef sErrDesc As String) As Long

        Dim sFuncName As String = String.Empty
        Dim oSalesOrder As SAPbobsCOM.Documents
        Dim sTransID As String = String.Empty
        Dim oUpdateSataus As clsARInvoice = New clsARInvoice
        Dim sCardCode As String = String.Empty
        Dim sWhsCode As String = String.Empty
        Dim sPOSNumber As String = String.Empty
        Dim sProject As String = String.Empty
        Dim sOrderNo As String = String.Empty
        Dim dIncomeDate As Date


        Try
            sFuncName = "UpdateEvent()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            oDataViewHeader = oDataset.Tables(0).DefaultView
            oDataViewLine = oDataset.Tables(1).DefaultView
            oDataViewPayment = oDataset.Tables(2).DefaultView

            oDTDistinctHeader = oDataViewHeader.Table.DefaultView.ToTable(True, "OrderNumber")

            For IntHeader As Integer = 0 To oDTDistinctHeader.Rows.Count - 1

                sTransID = oDTDistinctHeader.Rows(IntHeader).Item("OrderNumber").ToString.Trim

                oSalesOrder = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Start the Transaction", sFuncName)

                If oDICompany.InTransaction = False Then oDICompany.StartTransaction()


                If oSalesOrder.GetByKey(sTransID) Then

                    sCardCode = oSalesOrder.CardCode

                    dIncomeDate = oSalesOrder.DocDueDate


                    oDataViewLine.RowFilter = "OrderNumber = '" & sTransID & "'"

                    For IntRow As Integer = 0 To oDataViewLine.Count - 1

                        If oSalesOrder.Lines.ItemCode = oDataViewLine.Item(IntRow).Row("ProductCode").ToString.Trim AndAlso
                            oSalesOrder.Lines.LineNum = oDataViewLine.Item(IntRow).Row("ÒrderLine").ToString.Trim Then

                            oSalesOrder.Lines.SetCurrentLine(IntRow)

                            oSalesOrder.Lines.ItemCode = oDataViewLine.Item(IntRow).Row("ProductCode").ToString.Trim
                            oSalesOrder.Lines.WarehouseCode = oDataViewLine.Item(IntRow).Row("SalesOutler").ToString.Trim
                            oSalesOrder.Lines.UserFields.Fields.Item("U_EASIRcpt").Value = oDataViewLine.Item(IntRow).Row("PrtOnRcpt").ToString.Trim

                            oSalesOrder.Lines.UnitPrice = oDataViewLine.Item(IntRow).Row("Price").ToString.Trim
                            oSalesOrder.Lines.Quantity = oDataViewLine.Item(IntRow).Row("Quantity").ToString.Trim
                            oSalesOrder.Lines.ProjectCode = oDataViewLine.Item(IntRow).Row("RevenueCenter").ToString.Trim

                            oSalesOrder.SpecialLines.SetCurrentLine(IntRow)

                            oSalesOrder.SpecialLines.LineType = SAPbobsCOM.BoDocSpecialLineType.dslt_Text
                            oSalesOrder.SpecialLines.LineText = oDataViewLine.Item(IntRow).Row("LineText").ToString.Trim

                            oSalesOrder.Lines.Add()
                        Else

                            oSalesOrder.Lines.ItemCode = oDataViewLine.Item(IntRow).Row("ProductCode").ToString.Trim
                            oSalesOrder.Lines.WarehouseCode = oDataViewLine.Item(IntRow).Row("").ToString.Trim
                            oSalesOrder.Lines.UserFields.Fields.Item("U_EASIRcpt").Value = oDataViewLine.Item(IntRow).Row("PrtOnRcpt").ToString.Trim

                            oSalesOrder.Lines.UnitPrice = oDataViewLine.Item(IntRow).Row("Price").ToString.Trim
                            oSalesOrder.Lines.Quantity = oDataViewLine.Item(IntRow).Row("Quantity").ToString.Trim
                            oSalesOrder.Lines.ProjectCode = oDataViewLine.Item(IntRow).Row("RevenueCenter").ToString.Trim

                            oSalesOrder.SpecialLines.LineType = SAPbobsCOM.BoDocSpecialLineType.dslt_Text
                            oSalesOrder.SpecialLines.LineText = oDataViewLine.Item(IntRow).Row("LineText").ToString.Trim

                            oSalesOrder.Lines.Add()

                        End If

                        sWhsCode = oDataViewLine.Item(0).Row("SalesOutler").ToString.Trim
                        sProject = oDataViewLine.Item(0).Row("RevenueCenter").ToString.Trim
                        sOrderNo = oDataViewLine.Item(0).Row("OrderNumber").ToString.Trim

                    Next

                    lRetCode = oSalesOrder.Update()

                    If lRetCode <> 0 Then
                        sErrDesc = oDICompany.GetLastErrorDescription

                        Call WriteToLogFile(sErrDesc, sFuncName)
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)

                        oUpdateSataus.Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesOrderHdr")
                    Else

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling SalesOrder_Payment()", sFuncName)

                        oDataViewPayment.RowFilter = "SalesOrderNum = '" & sTransID & "'"

                        If SalesOrder_Payment(oDataViewPayment, oDICompany, sTransID, sOrderNo,
                                        sCardCode, sProject, sErrDesc) <> RTN_SUCCESS Then Throw New ArgumentException(sErrDesc)

                        If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Committed the Transaction ", sFuncName)

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Update_Status() ", sFuncName)

                        oUpdateSataus.Update_Status(sTransID, "", "SUCCESS", "", "SalesOrderHdr")

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                    End If

                End If

            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
            Return RTN_SUCCESS

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            oUpdateSataus.Update_Status(sTransID, sErrDesc, "FAIL", "", "SalesOrderHdr")
            If oDICompany.InTransaction = True Then oDICompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
            Return RTN_ERROR
        End Try

    End Function

    Function SalesOrder_Payment(ByRef oDataViewPayment As DataView, ByVal oDICompany As SAPbobsCOM.Company, _
                          ByVal sTransID As String, ByVal sOrderNo As String, ByVal sCardCode As String, _
                          ByVal sProject As String, ByRef sErrDesc As String) As Long

        Dim sFuncName As String = String.Empty
        Dim sPayDocEntry As String = String.Empty
        Dim lRetCode As Long
        Dim dIncomeDate As Date
        Dim sWhsCode As String = String.Empty
        Dim sPOSNumber As String = String.Empty
        Dim sSalesOrderNum As String = String.Empty
        Try

            Dim oIncomingPayment As SAPbobsCOM.Payments = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oIncomingPayments)
            Dim sCreditCard As String = String.Empty


            sWhsCode = oDataViewPayment.Item(0).Row("Outlet").ToString.Trim
            sPOSNumber = oDataViewPayment.Item(0).Row("POSNo").ToString.Trim
            dIncomeDate = oDataViewPayment.Item(0).Row("PaymentDate").ToString.Trim
            sSalesOrderNum = oDataViewPayment.Item(0).Row("SalesOrderNum").ToString.Trim

            oIncomingPayment.DocType = SAPbobsCOM.BoRcptTypes.rCustomer

            If sCardCode = "" Then
                sCardCode = oUpdateSataus.GetSingleValue("Select CardCode from OQUT where DocEntry='" & oDataViewLine.Item(0).Row("SalesQuotNum").ToString.Trim & "'",
                                                         oDICompany, sErrDesc)
            End If

            oIncomingPayment.CardCode = CStr(sCardCode)
            oIncomingPayment.DocDate = dIncomeDate
            oIncomingPayment.DueDate = dIncomeDate
            oIncomingPayment.DueDate = dIncomeDate

            For IntPayment As Integer = 0 To oDataViewPayment.Count - 1

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling GetSingleValue() for CreditCard ", sFuncName)

                sCreditCard = oUpdateSataus.GetSingleValue("select CreditCard  from OCRC where CardName =(select Name from [@TENDER] " &
                                             " where U_TenderCode ='" & CInt(oDataViewPayment.Item(IntPayment).Row("TenderCode").ToString.Trim) & "') ", _
                                                                          oDICompany, sErrDesc)
                If sCreditCard = 14 Then Continue For

                oIncomingPayment.CreditCards.CreditCard = sCreditCard

                oIncomingPayment.CreditCards.CreditType = SAPbobsCOM.BoRcptCredTypes.cr_Regular

                oIncomingPayment.CreditCards.CardValidUntil = "01/12/9999"
                oIncomingPayment.CreditCards.CreditCardNumber = "1234" 'oDataViewPayment.Item(IntPayment).Row("CrCardNum").ToString.Trim
                oIncomingPayment.CreditCards.VoucherNum = sWhsCode & "-" & CDate(dIncomeDate).ToString("yyMMdd") & "-" & sPOSNumber
                oIncomingPayment.CreditCards.CreditSum = CDbl(oDataViewPayment.Item(IntPayment).Row("PaymentAmount").ToString.Trim)
                oIncomingPayment.CreditCards.Add()


            Next

            oIncomingPayment.UserFields.Fields.Item("U_WHSCode").Value = sWhsCode
            oIncomingPayment.UserFields.Fields.Item("U_POSNo").Value = sPOSNumber
            oIncomingPayment.UserFields.Fields.Item("U_SONo").Value = sSalesOrderNum
            oIncomingPayment.ProjectCode = sProject

            oIncomingPayment.CashSum = 0

            lRetCode = oIncomingPayment.Add()

            If lRetCode <> 0 Then
                sErrDesc = oDICompany.GetLastErrorDescription
                Call WriteToLogFile(sErrDesc, sFuncName)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with ERROR", sFuncName)

                SalesOrder_Payment = RTN_ERROR
            Else
                oDICompany.GetNewObjectCode(sPayDocEntry)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with SUCCESS : " & sPayDocEntry, sFuncName)
            End If

            SalesOrder_Payment = RTN_SUCCESS

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return RTN_ERROR
        End Try
    End Function

    Function EventDeposit(ByRef oDataset As DataSet, ByVal oDICompany As SAPbobsCOM.Company _
                          , ByRef sErrDesc As String) As Long

        Dim sFuncName As String = String.Empty
        Dim sPayDocEntry As String = String.Empty
        Dim lRetCode As Long
        Dim dIncomeDate As Date
        Dim sWhsCode As String = String.Empty
        Dim sPOSNumber As String = String.Empty
        Dim sSalesOrderNum As String = String.Empty
        Dim sTransID As String = String.Empty

        Try

            oDataViewPayment = oDataset.Tables(0).DefaultView

            oDTDistinctHeader = oDataViewPayment.Table.DefaultView.ToTable(True, "SalesQuotNum")

            For IntHeader As Integer = 0 To oDTDistinctHeader.Rows.Count - 1

                sTransID = oDTDistinctHeader.Rows(IntHeader).Item("SalesQuotNum").ToString.Trim


                oDataViewPayment.RowFilter = "SalesQuotNum = '" & sTransID & "'"

                For IntRow As Integer = 0 To oDataViewPayment.Count - 1


                    Dim oIncomingPayment As SAPbobsCOM.Payments = oDICompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oIncomingPayments)
                    Dim sCreditCard As String = String.Empty


                    sWhsCode = oDataViewPayment.Item(0).Row("Outlet").ToString.Trim
                    sPOSNumber = oDataViewPayment.Item(0).Row("POSNo").ToString.Trim
                    dIncomeDate = oDataViewPayment.Item(0).Row("PaymentDate").ToString.Trim
                    sSalesOrderNum = oDataViewPayment.Item(0).Row("SalesOrderNum").ToString.Trim

                    oIncomingPayment.DocType = SAPbobsCOM.BoRcptTypes.rCustomer


                    sCardCode = oUpdateSataus.GetSingleValue("Select CardCode from OQUT where DocEntry='" & oDataViewPayment.Item(0).Row("SalesQuotNum").ToString.Trim & "'",
                                                             oDICompany, sErrDesc)


                    oIncomingPayment.CardCode = CStr(sCardCode)
                    oIncomingPayment.DocDate = dIncomeDate
                    oIncomingPayment.DueDate = dIncomeDate
                    oIncomingPayment.TaxDate = dIncomeDate


                    oIncomingPayment.Invoices.Add()

                    oDataViewPayment.RowFilter = "SalesOrderNum = '" & sTransID & "'"

                    For IntPayment As Integer = 0 To oDataViewPayment.Count - 1

                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling GetSingleValue() for CreditCard ", sFuncName)

                        sCreditCard = oUpdateSataus.GetSingleValue("select CreditCard  from OCRC where CardName =(select Name from [@TENDER] " &
                                                     " where U_TenderCode ='" & CInt(oDataViewPayment.Item(IntPayment).Row("TenderCode").ToString.Trim) & "') ", _
                                                                                  oDICompany, sErrDesc)
                        If sCreditCard = 14 Then Continue For

                        oIncomingPayment.CreditCards.CreditCard = sCreditCard

                        oIncomingPayment.CreditCards.CreditType = SAPbobsCOM.BoRcptCredTypes.cr_Regular

                        oIncomingPayment.CreditCards.CardValidUntil = "01/12/9999"
                        oIncomingPayment.CreditCards.CreditCardNumber = "1234" 'oDataViewPayment.Item(IntPayment).Row("CrCardNum").ToString.Trim
                        oIncomingPayment.CreditCards.VoucherNum = sWhsCode & "-" & CDate(dIncomeDate).ToString("yyMMdd") & "-" & sPOSNumber
                        oIncomingPayment.CreditCards.CreditSum = CDbl(oDataViewPayment.Item(IntPayment).Row("PaymentAmount").ToString.Trim)
                        oIncomingPayment.CreditCards.Add()

                    Next

                    oIncomingPayment.UserFields.Fields.Item("U_WHSCode").Value = sWhsCode
                    oIncomingPayment.UserFields.Fields.Item("U_POSNo").Value = sPOSNumber
                    oIncomingPayment.UserFields.Fields.Item("U_SONo").Value = sSalesOrderNum

                    oIncomingPayment.CashSum = 0

                    lRetCode = oIncomingPayment.Add()

                    If lRetCode <> 0 Then
                        sErrDesc = oDICompany.GetLastErrorDescription
                        Call WriteToLogFile(sErrDesc, sFuncName)
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with ERROR", sFuncName)
                        oUpdateSataus.Update_Status(sTransID, sErrDesc, "FAIL", "", "EventDeposit")

                        EventDeposit = RTN_ERROR
                    Else
                        oDICompany.GetNewObjectCode(sPayDocEntry)
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Incoming Payment Completed with SUCCESS : " & sPayDocEntry, sFuncName)
                        oUpdateSataus.Update_Status(sTransID, sErrDesc, "SUCCESS", "", "EventDeposit")
                    End If

                Next

            Next
            EventDeposit = RTN_SUCCESS

        Catch ex As Exception
            sErrDesc = ex.Message
            Call WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return RTN_ERROR
        End Try
    End Function

    Function EventOrder_DataSet(ByVal sConnectionString As String) As DataSet

        Dim oDataSet As DataSet
        Dim oDataAdapter, oDACondition As SqlDataAdapter
        Dim oDataTable, oDTCondition As DataTable
        Dim sQuery As String = String.Empty
        Dim sFuncName As String = String.Empty

        Try
            sFuncName = "EventOrder_DataSet()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)
            oDataSet = New DataSet

            sQuery = "SELECT [OrderNumber],[CustomerAccountNo],[CustomerFullName] ,[ContactName] ,[BillingAddress] ,[Telephone]  ,[Email] ,[EventOrderNumber] ,[PersonInCharge]" & _
                " ,[DistributionDate] ,[EventDate]  ,[EventStartTime] ,[EventTimeEnd] ,[FoodTimeStart]  ,[FoodTimeEnd]   ,[BvgTimeStart] ,[BvgTimeEnd]  ,[EventVenue] " & _
                " ,[EventFunction]  ,[OutletCode]  ,[EventSetup]  ,[GTDAttendance] ,[EXPAttendance],[AudioVisual] ,[BanquetOperation] ,[Linens] ,[Signage] " & _
                " ,[FinanceInstructions] ,[ReqDownPaymtAmt],[RevenueCenter] ,[GrossAmount] ,[PaidToDate] ,[EventStatus],[RevenueCenterName] " & _
                " from SalesOrderHdr where isnull(Status,'')='' and isnull(ReceiveDate,'')='' "


            oDataAdapter = New SqlDataAdapter(sQuery, sConnectionString)
            oDataTable = New DataTable
            oDataAdapter.Fill(oDataTable)
            oDataSet.Tables.Add(oDataTable)
            If oDataSet.Tables(0).Rows.Count > 0 Then

                'Get a DocEntry for Read the Lines Level Values Based on Respective DocEntry

                sQuery = ""
                sQuery = "declare  @diststring as varchar(max)"
                sQuery += vbCrLf + "select @diststring=coalesce(@diststring+ ''', ''','')+convert(varchar,ID)from SalesOrderHdr where isnull(Status,'')='' and isnull(ReceiveDate,'')=''"
                sQuery += vbCrLf + "select  ''''+@diststring+ '''' as TransID "
                oDTCondition = New DataTable
                oDACondition = New SqlDataAdapter(sQuery, sConnectionString)
                oDACondition.Fill(oDTCondition)


                'To Get Get a Line Level Data's 

                sQuery = ""
                sQuery += vbCrLf + "Select [OrderNumber],[OrderLine],[VisualOrder],[SalesOultlet],[ProductCode] ,[PrtOnRcpt],[Price] ,[Quantity] ,[GrossAmount] ,[RevenueCenter]" & _
                    " ,[LineText]  from [SalesOrderDET] where OrderNumber in (" & oDTCondition.Rows(0)("TransID").ToString & ")  "

                oDataAdapter = New SqlDataAdapter(sQuery, sConnectionString)
                oDataTable = New DataTable
                oDataAdapter.Fill(oDataTable)
                oDataSet.Tables.Add(oDataTable)

         
                'To Get the Payment Details:
                sQuery = ""
                sQuery += vbCrLf + "select [SalesOrderNum],[TenderCode],[PaymentAmount],[PaymentDate],[Outlet] ,[POSNo] ,[ChqNo] from [SalesOrderPymt]  " & _
                    " where SalesOrderNum in (" & oDTCondition.Rows(0)("TransID").ToString & ")  "

                oDataAdapter = New SqlDataAdapter(sQuery, sConnectionString)
                oDataTable = New DataTable
                oDataAdapter.Fill(oDataTable)
                oDataSet.Tables.Add(oDataTable)

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                Return oDataSet
            Else
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                Return Nothing
            End If
        Catch ex As Exception
            Call WriteToLogFile(ex.Message, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return Nothing
        End Try
    End Function

    Function EventDeposit_DataSet(ByVal sConnectionString As String) As DataSet

        Dim oDataSet As DataSet
        Dim oDataAdapter As SqlDataAdapter
        Dim oDataTable As DataTable
        Dim sQuery As String = String.Empty
        Dim sFuncName As String = String.Empty

        Try
            sFuncName = "EventOrder_DataSet()"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)
            oDataSet = New DataSet

                'To Get the Payment Details:
            sQuery = ""
            sQuery += vbCrLf + "select [SalesQuotNum],[TenderCode],[PaymentAmount],[PaymentDate],[Outlet] ,[POSNo] ,[ChqNo] from EventDeposit  " & _
                " where isnull(Status,'')='' and isnull(ReceiveDate,'')=''"
            oDataAdapter = New SqlDataAdapter(sQuery, sConnectionString)
            oDataTable = New DataTable
            oDataAdapter.Fill(oDataTable)
            oDataSet.Tables.Add(oDataTable)

            If oDataSet.Tables(0).Rows.Count > 0 Then
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                Return oDataSet
            Else
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with SUCCESS", sFuncName)
                Return Nothing
            End If


        Catch ex As Exception
            Call WriteToLogFile(ex.Message, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Completed with ERROR", sFuncName)
            Return Nothing
        End Try
    End Function


End Class
